import {
  HttpException,
  HttpStatus,
  Injectable,
  UploadedFile,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Not, Repository } from 'typeorm';
import { Address } from './entities/address.entity';
import { CreateAddressDto } from './dto/create-address.dto';
import { UpdateAddressDto } from './dto/update-address.dto';

@Injectable()
export class AddressService {
  @InjectRepository(Address)
  private addressRepository: Repository<Address>;

  async create(createAddressDto: CreateAddressDto, userId: number) {
    const { isDefault = false } = createAddressDto;

    if (isDefault) {
      // 如果设置为默认地址，需要将其他地址设置为非默认
      await this.addressRepository.update(
        { user: { id: userId } },
        { isDefault: false },
      );
    }

    const address = new Address();
    Object.assign(address, createAddressDto);
    address.user = { id: userId } as any;

    try {
      await this.addressRepository.save(address);
      return '新增成功';
    } catch (e) {
      throw new HttpException('新增失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async findAll(userId: number) {
    const addresses = await this.addressRepository.find({
      where: { user: { id: userId } },
      order: {
        isDefault: 'DESC',
        createTime: 'DESC',
      },
    });

    return addresses;
  }

  async findOne(id: number, userId: number) {
    const address = await this.addressRepository.findOne({
      where: { id, user: { id: userId } },
    });

    if (!address) {
      throw new HttpException('地址不存在', HttpStatus.BAD_REQUEST);
    }

    return address;
  }

  async update(id: number, updateAddressDto: UpdateAddressDto, userId: number) {
    const address = await this.addressRepository.findOne({
      where: { id, user: { id: userId } },
    });

    if (!address) {
      throw new HttpException('地址不存在', HttpStatus.BAD_REQUEST);
    }

    const { isDefault } = updateAddressDto;

    if (isDefault) {
      // 如果设置为默认地址，需要将其他地址设置为非默认
      await this.addressRepository.update(
        { user: { id: userId }, id: Not(id) },
        { isDefault: false },
      );
    }

    Object.assign(address, updateAddressDto);

    try {
      await this.addressRepository.save(address);
      return '更新成功';
    } catch (e) {
      throw new HttpException('更新失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async remove(id: number, userId: number) {
    const address = await this.addressRepository.findOne({
      where: { id, user: { id: userId } },
    });

    if (!address) {
      throw new HttpException('地址不存在', HttpStatus.BAD_REQUEST);
    }

    try {
      await this.addressRepository.remove(address);
      return '删除成功';
    } catch (e) {
      throw new HttpException('删除失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async uploadImage(@UploadedFile() file: any) {
    return {
      url: `/uploads/images/${file.filename}`,
    };
  }
}
